package com.zjw.touchscreen.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjw.touchscreen.server.entity.VersionEntity;
import com.zjw.touchscreen.server.mapper.VersionMapper;
import com.zjw.touchscreen.server.service.VersionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@Transactional
public class VersionServiceImpl extends ServiceImpl<VersionMapper, VersionEntity> implements VersionService {

    @Override
    public VersionEntity lastVersion(Integer id) {
        VersionEntity version = getById(id);
        List<VersionEntity> versions = lambdaQuery()
                .gt(Objects.nonNull(version.getCreatedDatetime()), VersionEntity::getCreatedDatetime, version.getCreatedDatetime())
                .list();
        if (CollectionUtils.isEmpty(versions)) {
            return version;
        }
        Boolean force = false;
        for (VersionEntity newVersion : versions) {
            if (newVersion.getIsForce()) {
                force = true;
                break;
            }
        }
        version = versions.get(versions.size() - 1);
        version.setIsForce(force);
        return version;
    }
}
